<template>
    <infinite-scroll-select
        v-model="modelValue"
        :options="tableData"
        optionLabel="username"
        optionKey="username"
        :optionValue="(e) => e.username"
        :loading="loading"
        :has-more="hasMore"
        @load-more="loadMore"
        placeholder="请选择"
        clearable
        filterable
        multiple
    />
</template>


<script setup>
import InfiniteScrollSelect from '../InfiniteScrollSelect/index.vue'
import { listApi } from '@/api/user/index.api'
import useToggle from "@/hooks/useToggle";
const [loading, _, setLoading] = useToggle();

const props = defineProps({
  modelValue: { type: [String, Number], default: null },
});
const emit = defineEmits(['update:modelValue']);
const modelValue = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
});
const tableData = ref([])
const paging = ref({
  size: 100,
  page: 1,
  total: 0,
})

const hasMore = computed(() => {
  return tableData.value.length < paging.value.total
})

const loadMore = () => {
    if (hasMore.value) loadData()
}

const loadData = () => {
    paging.value.page++
    getList()
}

const getList = () => {
    setLoading(true)
    listApi({
        page: paging.value.page,
        size: paging.value.size
    }).then(res => {
        paging.value.total = res.count
        if (paging.value.page > 1) {
            tableData.value = [...tableData.value, ...res.rows]
            return
        }
        tableData.value = res.rows
    }).finally(() => {
        setLoading(false)
    })
}

onMounted(() => {
    getList()
})
</script>
